using System.Collections.Generic;
using System.Linq;
using JetBrains.Annotations;
using Voodoo.Sauce.Common.Utils;
using Voodoo.Sauce.Core;
using Voodoo.Sauce.Debugger;
using Voodoo.Sauce.Internal.IAP;

namespace Voodoo.Sauce.IAP
{
	internal class IAPDebugManager : IPurchaseDelegateWithInfo, IPurchaseDelegateBase
	{
		private const string CALLBACK_PURCHASE_SUCCESS_WITH_TRANSACTION_ID_FORMAT = "You have successfully bought this product. With transaction ID: {0}";

		private const string LIGHT_MESSAGE_NO_PRODUCTS = "There is no product in this project.\nYou can add them in the VoodooSettings.";

		private const string LIGHT_MESSAGE_INITIALIZING = "Waiting for the In-App Purchase initialization...";

		private const string LIGHT_MESSAGE_DISABLED = "In-App Purchase isn't activated on your project.";

		private const string LIGHT_MESSAGE_NOT_INSTALLED = "In-App Purchase isn't installed on your project.";

		private const string ERROR_MESSAGE_HEADER = "In-App purchase initialization has failed.\n";

		private const string ERROR_MESSAGE_APP_NOT_KNOWN = "In-App purchase initialization has failed.\nIs your App correctly uploaded on the relevant publisher console?";

		private const string ERROR_MESSAGE_PURCHASING_UNAVAILABLE = "In-App purchase initialization has failed.\nBilling is disabled.";

		private const string ERROR_MESSAGE_NO_PRODUCTS = "In-App purchase initialization has failed.\nNo products available for purchase.";

		private readonly IAPCore _iap;

		private readonly IAPDebugScreen _screen;

		private bool _initializationStarted;

		private bool _initialized;

		private VoodooSettings _voodooSettings;

		internal IAPDebugManager(IAPDebugScreen screen, VoodooSettings voodooSettings)
		{
			_screen = screen;
			_iap = VoodooSauceCore.GetInAppPurchase();
			_voodooSettings = voodooSettings;
		}

		internal void OnScreenDisplayed()
		{
			if (!_initializationStarted)
			{
				Initialize();
			}
			else if (_initialized)
			{
				RefreshDisplayedProducts();
			}
			RefreshVoodooPremiumToggle();
		}

		private void Initialize()
		{
			_screen.DisplayLightMessage("Waiting for the In-App Purchase initialization...");
			_screen.EnableRestoreButton(PlatformUtils.UNITY_IOS || PlatformUtils.UNITY_ANDROID);
			_initializationStarted = true;
		}

		private IAPDebugProduct.Status GetProductStatus(ProductReceivedInfo product)
		{
			if (PlatformUtils.UNITY_ANDROID && !ProductDescriptor.IsValidAndroidProductId(product.ProductId))
			{
				return IAPDebugProduct.Status.BadID;
			}
			if (!product.IsAvailable)
			{
				return IAPDebugProduct.Status.Missing;
			}
			if (!string.IsNullOrEmpty(product.TransactionID))
			{
				return IAPDebugProduct.Status.Owned;
			}
			return IAPDebugProduct.Status.Available;
		}

		private void RefreshDisplayedProducts()
		{
			List<IAPDebugProduct> list = _iap.GetProducts()?.Select((ProductReceivedInfo product) => new IAPDebugProduct(product.ProductId, product.ProductType.ToString(), product.LocalizedPriceInfo.ToString(), GetProductStatus(product), product.IsAvailable)).ToList();
			if (list != null && list.Count > 0)
			{
				_screen.CreateProductsButtons(list);
			}
			else
			{
				_screen.DisplayLightMessage("There is no product in this project.\nYou can add them in the VoodooSettings.");
			}
		}

		internal void OnVoodooPremiumToggle(bool isOn)
		{
			VoodooPremium.SetEnabledPremium(isOn);
		}

		private void RefreshVoodooPremiumToggle()
		{
		}

		public void OnInitializeSuccess()
		{
			RefreshDisplayedProducts();
			_initialized = true;
		}

		public void OnInitializeFailure(VoodooInitializationFailureReason reason)
		{
			switch (reason)
			{
			case VoodooInitializationFailureReason.PurchasingUnavailable:
				_screen.DisplayErrorMessage("In-App purchase initialization has failed.\nBilling is disabled.");
				break;
			case VoodooInitializationFailureReason.AppNotKnown:
				_screen.DisplayErrorMessage("In-App purchase initialization has failed.\nIs your App correctly uploaded on the relevant publisher console?");
				break;
			case VoodooInitializationFailureReason.NoProductsAvailable:
				_screen.DisplayErrorMessage("In-App purchase initialization has failed.\nNo products available for purchase.");
				break;
			case VoodooInitializationFailureReason.IAPModuleNotInstalled:
				_screen.DisplayLightMessage("In-App Purchase isn't installed on your project.");
				break;
			case VoodooInitializationFailureReason.IAPModuleDisabled:
				_screen.DisplayLightMessage("In-App Purchase isn't activated on your project.");
				break;
			}
		}

		public void OnPurchaseComplete(ProductReceivedInfo productInfo, PurchaseValidation purchaseValidation)
		{
			if (_screen.gameObject.activeInHierarchy)
			{
				Voodoo.Sauce.Debugger.Debugger.DisplayPopup($"You have successfully bought this product. With transaction ID: {productInfo.TransactionID}");
			}
			RefreshDisplayedProducts();
			if (productInfo.ProductId == _voodooSettings.NoAdsBundleId)
			{
				VoodooPremium.SetEnabledPremium();
				RefreshVoodooPremiumToggle();
			}
		}

		public void OnPurchaseFailure(VoodooPurchaseFailureReason reason, [CanBeNull] ProductReceivedInfo productInfo, string description)
		{
			if (_screen.gameObject.activeInHierarchy)
			{
				string text = reason switch
				{
					VoodooPurchaseFailureReason.PaymentDeclined => "This transaction has stopped because the payment failed.", 
					VoodooPurchaseFailureReason.DuplicateTransaction => "This transaction has failed because you already did it.", 
					VoodooPurchaseFailureReason.PurchasingUnavailable => "The In-App Purchasing is not available.", 
					VoodooPurchaseFailureReason.ExistingPurchasePending => "This transaction has stopped because the same one is currently pending.", 
					VoodooPurchaseFailureReason.ProductUnavailable => "You can't buy this product because it's unavailable.", 
					VoodooPurchaseFailureReason.SignatureInvalid => "This purchase has been canceled because its signature validation has failed.\nDid you correctly update the GoogleTangle?", 
					VoodooPurchaseFailureReason.UserCancelled => "You have canceled this purchase.", 
					VoodooPurchaseFailureReason.IAPValidationFailed => "This purchase has been canceled because its validation has failed.", 
					VoodooPurchaseFailureReason.IAPValidationAbortedEmptyReceipt => "This purchase has been canceled because its validation has failed.\nThe transaction has had no receipt.", 
					_ => "An unknown error has just happened, this transaction has failed.", 
				};
				if (!string.IsNullOrEmpty(description))
				{
					text = text + "\nFailure description: " + description;
				}
				text = text + "\nProduct ID: " + productInfo?.ProductId;
				if (!string.IsNullOrEmpty(productInfo?.TransactionID))
				{
					text = text + "\nTransaction ID: " + productInfo.TransactionID;
				}
				RefreshVoodooPremiumToggle();
				Voodoo.Sauce.Debugger.Debugger.DisplayPopup(text);
			}
		}
	}
}
